// 全局状态管理
import { reactive } from 'vue'

// 用户状态
const userState = reactive({
  isLoggedIn: false,
  userInfo: {
    id: '',
    username: '',
    avatar: '',
    bio: '',
    following: 0,
    followers: 0,
    // 会员相关信息
    membershipLevel: 0, // 0: 普通用户, 1: 黄金会员, 2: 铂金会员, 3: 钻石会员
    membershipExpiry: '', // 会员到期日期
    points: 0 // 用户积分
  },
  myNotes: [],
  myDrafts: [],
  likedNotes: [],
  followingUsers: [],
  publishedVideos: [],
  likedVideos: []
})

// 验证登录
const validateLogin = (username, password) => {
  try {
    // 从本地存储获取用户列表
    const users = JSON.parse(localStorage.getItem('users')) || []
    
    // 查找用户并验证密码
    const user = users.find(u => u.username === username && u.password === password)
    
    return !!user
  } catch (error) {
    console.error('Login validation failed:', error)
    return false
  }
}

// 登录
const login = (userData) => {
  try {
    // 检查是否为管理员账号
    const isAdmin = userData.username === 'root' && userData.password === 'root'
    
    if (isAdmin) {
      // 设置管理员状态
      userState.isLoggedIn = true
      userState.userInfo = {
        id: 'admin',
        username: 'root',
        avatar: 'https://picsum.photos/200/200?random=999',
        bio: '系统管理员',
        following: 0,
        followers: 0,
        isAdmin: true
      }
      
      // 保存到本地存储
      localStorage.setItem('userState', JSON.stringify({
        isLoggedIn: userState.isLoggedIn,
        userInfo: userState.userInfo
      }))
      
      return { success: true, isAdmin: true }
    }
    
    // 普通用户登录逻辑
    // 从本地存储获取用户列表，找到完整的用户信息
    const users = JSON.parse(localStorage.getItem('users')) || []
    const fullUserInfo = users.find(u => u.username === userData.username)
    
    // 设置用户状态
    userState.isLoggedIn = true
    userState.userInfo = {
      ...userState.userInfo,
      ...userData,
      ...fullUserInfo,
      avatar: userData.avatar || fullUserInfo?.avatar || `https://picsum.photos/200/200?random=${Math.floor(Math.random() * 100)}`,
      id: userData.id || fullUserInfo?.id || Math.random().toString(36).substr(2, 9),
      following: userData.following || fullUserInfo?.following || 0,
      followers: userData.followers || fullUserInfo?.followers || 0,
      bio: userData.bio || fullUserInfo?.bio || '',
      // 会员相关信息
      membershipLevel: userData.membershipLevel || fullUserInfo?.membershipLevel || 0,
      membershipExpiry: userData.membershipExpiry || fullUserInfo?.membershipExpiry || '',
      points: userData.points || fullUserInfo?.points || 0,
      isAdmin: false
    }
    
    // 保存到本地存储
    localStorage.setItem('userState', JSON.stringify({
      isLoggedIn: userState.isLoggedIn,
      userInfo: userState.userInfo
    }))
    
    // 初始化用户数据
    initializeUserData()
    
    return { success: true, isAdmin: false }
  } catch (error) {
    console.error('Login failed:', error)
    throw error
  }
}

// 更新用户信息
const updateUserInfo = (updatedInfo) => {
  // 更新用户信息
  userState.userInfo = {
    ...userState.userInfo,
    ...updatedInfo
  }
  
  // 保存到本地存储
  localStorage.setItem('userState', JSON.stringify({
    isLoggedIn: userState.isLoggedIn,
    userInfo: userState.userInfo
  }))
  
  // 同时更新用户列表中的信息
  let users = JSON.parse(localStorage.getItem('users')) || []
  const userIndex = users.findIndex(u => u.id === userState.userInfo.id)
  if (userIndex !== -1) {
    users[userIndex] = {
      ...users[userIndex],
      ...updatedInfo
    }
    localStorage.setItem('users', JSON.stringify(users))
  }
}

// 检查会员是否有效
const checkMembershipValid = () => {
  if (!userState.userInfo.membershipExpiry) return false;
  const expiryDate = new Date(userState.userInfo.membershipExpiry);
  const now = new Date();
  return expiryDate > now;
}

// 获取会员等级名称
const getMembershipLevelName = () => {
  if (!checkMembershipValid()) return '普通用户';
  const level = userState.userInfo.membershipLevel;
  switch(level) {
    case 1: return '黄金会员';
    case 2: return '铂金会员';
    case 3: return '钻石会员';
    default: return '普通用户';
  }
}

// 计算会员剩余天数
const getMembershipDaysRemaining = () => {
  if (!checkMembershipValid()) return 0;
  const expiryDate = new Date(userState.userInfo.membershipExpiry);
  const now = new Date();
  const diffTime = Math.abs(expiryDate - now);
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}

// 添加积分
const addPoints = (points) => {
  userState.userInfo.points += points;
  updateUserInfo({ points: userState.userInfo.points });
}

// 消费积分
const spendPoints = (points) => {
  if (userState.userInfo.points >= points) {
    userState.userInfo.points -= points;
    updateUserInfo({ points: userState.userInfo.points });
    return true;
  }
  return false;
}

// 登出
const logout = () => {
  userState.isLoggedIn = false
  userState.userInfo = {
    id: '',
    username: '',
    avatar: '',
    bio: '',
    following: 0,
    followers: 0
  }
  
  // 清除本地存储
  localStorage.removeItem('userState')
  
  // 清空用户数据
  userState.myNotes = []
  userState.myDrafts = []
  userState.likedNotes = []
  userState.followingUsers = []
}

// 检查登录状态
const checkLogin = () => {
  try {
    const savedState = localStorage.getItem('userState')
    if (savedState) {
      const state = JSON.parse(savedState)
      if (state.isLoggedIn) {
        userState.isLoggedIn = true
        userState.userInfo = state.userInfo
        initializeUserData()
      }
    }
  } catch (error) {
    console.error('Failed to load user state:', error)
  }
}

// 初始化用户数据
const initializeUserData = () => {
  // 加载用户的笔记
  try {
    const notes = JSON.parse(localStorage.getItem('notes')) || mockNotes
    userState.myNotes = notes.filter(note => note.user?.id === userState.userInfo.id)
  } catch (error) {
    console.error('Failed to load notes:', error)
    userState.myNotes = []
  }
  
  // 加载用户的草稿
  try {
    const drafts = JSON.parse(localStorage.getItem('drafts')) || []
    userState.myDrafts = drafts.filter(draft => draft.user?.id === userState.userInfo.id)
  } catch (error) {
    console.error('Failed to load drafts:', error)
    userState.myDrafts = []
  }
  
  // 加载用户喜欢的笔记
  try {
    const likedNotes = JSON.parse(localStorage.getItem('likedNotes')) || []
    userState.likedNotes = likedNotes
  } catch (error) {
    console.error('Failed to load liked notes:', error)
    userState.likedNotes = []
  }
  
  // 加载用户关注的人
  try {
    const followingUsers = JSON.parse(localStorage.getItem('followingUsers')) || []
    userState.followingUsers = followingUsers
  } catch (error) {
    console.error('Failed to load following users:', error)
    userState.followingUsers = []
  }
  
  // 初始化视频数据
  try {
    const videos = JSON.parse(localStorage.getItem('videos')) || []
    userState.publishedVideos = videos.filter(video => video.userId === userState.userInfo.id)
    userState.likedVideos = videos.filter(video => {
      const likedVideoIds = JSON.parse(localStorage.getItem('likedVideoIds') || '[]')
      return likedVideoIds.includes(video.id)
    })
  } catch (error) {
    console.error('Failed to load video data:', error)
    userState.publishedVideos = []
    userState.likedVideos = []
  }
}

// 获取我的笔记
const getMyNotes = () => {
  return userState.myNotes
}

// 获取草稿
const getDrafts = () => {
  return userState.myDrafts
}

// 获取我喜欢的笔记
const getLikedNotes = () => {
  return userState.likedNotes
}

// 获取我关注的用户
const getFollowing = () => {
  return userState.followingUsers
}

// 模拟笔记数据
const mockNotes = [
  {
    id: '1',
    title: '今日穿搭分享',
    content: '今天的穿搭以简约为主，白色T恤搭配牛仔裤，简单又时尚。',
    tags: ['穿搭', '日常', '简约'],
    user: {
      id: 'user1',
      username: '时尚达人',
      avatar: 'https://picsum.photos/200/200?random=1'
    },
    likes: 128,
    comments: 24,
    time: '2023-06-15T10:30:00Z',
    images: ['https://picsum.photos/600/400?random=101']
  },
  {
    id: '2',
    title: '夏日必备防晒好物',
    content: '夏天到了，防晒可是重中之重！这款防晒霜清爽不油腻，防晒效果特别好。',
    tags: ['防晒', '美妆', '夏日'],
    user: {
      id: 'user2',
      username: '美妆博主',
      avatar: 'https://picsum.photos/200/200?random=2'
    },
    likes: 256,
    comments: 48,
    time: '2023-06-14T15:20:00Z',
    images: ['https://picsum.photos/600/400?random=102']
  },
  {
    id: '3',
    title: '周末探店分享',
    content: '这家咖啡馆环境超级棒，咖啡也很好喝，适合周末和朋友小聚。',
    tags: ['咖啡', '探店', '周末'],
    user: {
      id: 'user3',
      username: '美食爱好者',
      avatar: 'https://picsum.photos/200/200?random=3'
    },
    likes: 189,
    comments: 36,
    time: '2023-06-13T09:15:00Z',
    images: ['https://picsum.photos/600/400?random=103']
  },
  {
    id: '4',
    title: '居家健身小技巧',
    content: '在家也能高效健身！这几个动作简单易学，效果还特别好。',
    tags: ['健身', '居家', '健康'],
    user: {
      id: 'user4',
      username: '健身教练',
      avatar: 'https://picsum.photos/200/200?random=4'
    },
    likes: 320,
    comments: 64,
    time: '2023-06-12T16:45:00Z',
    images: ['https://picsum.photos/600/400?random=104']
  },
  {
    id: '5',
    title: '读书心得分享',
    content: '最近读完了《小王子》，感触很深，分享一些我的读书心得。',
    tags: ['读书', '心得', '文学'],
    user: {
      id: 'user5',
      username: '文艺青年',
      avatar: 'https://picsum.photos/200/200?random=5'
    },
    likes: 156,
    comments: 42,
    time: '2023-06-11T14:30:00Z',
    images: ['https://picsum.photos/600/400?random=105']
  },
  {
    id: '6',
    title: '旅行攻略：丽江古城',
    content: '刚从丽江回来，整理出了一份超详细的旅行攻略，想去的小伙伴赶紧收藏！',
    tags: ['旅行', '攻略', '丽江'],
    user: {
      id: 'user6',
      username: '旅行博主',
      avatar: 'https://picsum.photos/200/200?random=6'
    },
    likes: 432,
    comments: 86,
    time: '2023-06-10T11:20:00Z',
    images: ['https://picsum.photos/600/400?random=106']
  }
]

// 初始化时检查登录状态
checkLogin()

// 导出状态和方法
export default userState
export { 
  userState, 
  validateLogin, 
  login, 
  logout, 
  checkLogin, 
  getMyNotes, 
  getDrafts, 
  getLikedNotes, 
  getFollowing,
  updateUserInfo,
  checkMembershipValid,
  getMembershipLevelName,
  getMembershipDaysRemaining,
  addPoints,
  spendPoints
}